﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Activities;
using System.IO;

namespace TfsExtensions.Build.Activities
{
    public sealed class CopyOutputToChmFolders : CodeActivity
    {
        [RequiredArgument]
        public InArgument<string> WorkingFolder { get; set; }

        [RequiredArgument]
        public InArgument<string> ChmFolderName { get; set; }


        // If your activity returns a value, derive from CodeActivity<TResult>
        // and return the value from the Execute method.
        protected override void Execute(CodeActivityContext context)
        {
            var workingFolder = this.WorkingFolder.Get(context);
            var chmFolderName = this.ChmFolderName.Get(context);

            DirectoryInfo source = new DirectoryInfo(string.Format(@"{0}\icons", workingFolder));
            DirectoryInfo target = new DirectoryInfo(string.Format(@"{0}\icons", chmFolderName));

            this.CopyAll(source, target);

            source = new DirectoryInfo(string.Format(@"{0}\scripts", workingFolder));
            target = new DirectoryInfo(string.Format(@"{0}\scripts", chmFolderName));

            this.CopyAll(source, target);

            source = new DirectoryInfo(string.Format(@"{0}\styles", workingFolder));
            target = new DirectoryInfo(string.Format(@"{0}\styles", chmFolderName));

            this.CopyAll(source, target);

            source = new DirectoryInfo(string.Format(@"{0}\media", workingFolder));
            target = new DirectoryInfo(string.Format(@"{0}\media", chmFolderName));

            this.CopyAll(source, target);
        }

        private void CopyAll(DirectoryInfo source, DirectoryInfo target)
        {
            // Check if the target directory exists, if not, create it.
            if (Directory.Exists(target.FullName) == false)
            {
                Directory.CreateDirectory(target.FullName);
            }

            // Copy each file into it’s new directory.
            foreach (FileInfo fi in source.GetFiles())
            {
                fi.CopyTo(Path.Combine(target.ToString(), fi.Name), true);
            }

            // Copy each subdirectory using recursion.
            foreach (DirectoryInfo diSourceSubDir in source.GetDirectories())
            {
                DirectoryInfo nextTargetSubDir =
                    target.CreateSubdirectory(diSourceSubDir.Name);
                CopyAll(diSourceSubDir, nextTargetSubDir);
            }
        }
    }
}
